//在文件夹apps下生成所需的路由加载文件
var fs = require('fs');
var path = require('path');

var childRoutes = new Array();
function scanFolder(path, defaultFile, defalutArray) {
    var basePath = path,
        entrys = defalutArray || [],
        walk = function(path, entrys){
            var files = fs.readdirSync(path);
            files.forEach(function(item) {
                var tmpPath = path + '/' + item;

                if (item == defaultFile) {
                    var requirePath = tmpPath.substring(basePath.length+1);
                    if (requirePath == './404/index.js' || requirePath == './index.js') {
                        return;
                    }
                    requirePath=requirePath.substr(0,requirePath.lastIndexOf(defaultFile));
                    entrys.push(requirePath);
                }
                var stats = fs.statSync(tmpPath);
                if (stats.isDirectory()) {
                    walk(tmpPath, entrys);
                }
            });
        };

    walk(path, entrys);
}

scanFolder('../../ui/pages', 'index.html', childRoutes);

var routeFilePath = '../../ui/route.js';

var data = "define([],function(){ return[";

for (i in childRoutes) {
    data += '\n\r {url:"'+childRoutes[i]+'",js:"pages/'+childRoutes[i]+'index.js",html:"pages/'+childRoutes[i]+'index.html"},'
}
data=data.substr(0,data.lastIndexOf(","));
data += "\r\n]\r\n}\r\n)"
//写到相应的文件夹
fs.writeFileSync(routeFilePath, data, {encoding:'utf-8'});